package com.digitalchina.lxnsy.activity.farmVideo;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.SmallVideoDetailVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.JointImageUrl;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.MediaController;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.okhttputils.model.HttpParams;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.ruffian.library.RTextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SmallVideoActivity extends BaseActivity {


    @Bind(R.id.VideoView)
    PLVideoTextureView mVideoView;
    @Bind(R.id.LoadingView)
    LinearLayout mLoadingView;
    @Bind(R.id.img_fullscreen)
    ImageView imgFullscreen;
    @Bind(R.id.tv_collect)
    RTextView tvCollect;
    @Bind(R.id.tv_zan)
    RTextView tvZan;
    @Bind(R.id.tv_comment)
    RTextView tvComment;
    @Bind(R.id.tv_share)
    RTextView tvShare;
    @Bind(R.id.sdv_img)
    SimpleDraweeView sdvImg;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_follow)
    TextView tvFollow;

    private String mVideoPath = "";
    private boolean isStore = false;
    private boolean isZan = false;

    private static final int MESSAGE_ID_RECONNECTING = 0x01;
    private MediaController mMediaController;
    private int mRotation = 0;
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT; //default
    private boolean mIsActivityPaused = true;
    private int mIsLiveStreaming = 0;

    private String videoID = "";
    private SmallVideoDetailVO mVO;

    @Override
    public void setLayout() {
        setTitle("小视频");
        setContentLayout(R.layout.activity_small_video);
    }

    private void setOptions(int codecType) {
        AVOptions options = new AVOptions();

        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_PROBESIZE, 128 * 1024);
        // Some optimization with buffering mechanism when be set to 1
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, codecType);

        // whether start play automatically after prepared, default value is 1
        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);
        mVideoView.setAVOptions(options);


    }

    @Override
    public void initMember() {

        videoID = (String) getIntent().getSerializableExtra("msg");

        isStore();


        HttpParams params = new HttpParams();
        params.put("userAccId", UserXML.getUserId(activity));
        params.put("id", videoID);

        OkHttpUtil.post(activity, URL.URL_GET_AGR_VIDEO_DETAIL, "", params, mHandler, MSG_S_0, MSG_F_0);


//        if (getIntent().hasExtra("TrainingListVO")) {
//            trainingListVO = (TrainingListVO) getIntent().getSerializableExtra("TrainingListVO");
//            mVideoPath = URL.SERVER_VIDEO + trainingListVO.getVideo();
//
//            // 浏览次数统计
//        BusinessAccount.appBrowse(this, trainingListVO.getId(), "5", trainingListVO.getName(), mVideoPath, mHandler);
//        } else {
//            mVideoPath = (String) getIntent().getSerializableExtra("path");
//        }


        mVideoView.setBufferingIndicator(mLoadingView);
        mLoadingView.setVisibility(View.VISIBLE);
        // If you want to fix display orientation such as landscape, you can use the code show as follow
        //
        // if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //     mVideoView.setPreviewOrientation(0);
        // }
        // else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        //     mVideoView.setPreviewOrientation(270);
        // }

        // 1 -> hw codec enable, 0 -> disable [recommended]
        setOptions(AVOptions.MEDIA_CODEC_AUTO);

        // You can mirror the display
        // mVideoView.setMirror(true);

        // You can also use a custom `MediaController` widget
        mMediaController = new MediaController(this, false, mIsLiveStreaming == 1);
        mVideoView.setMediaController(mMediaController);

        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);


    }

    //收藏
    protected void store() {
        isStore = true;
        HttpParams params = new HttpParams();
        params.put("user", UserXML.getUserId(activity));
        params.put("title", mVO.getTitle());
        params.put("picture", mVO.getCoverImg());
        params.put("contentCtg", mVO.getSecondType().getCode());
        params.put("price", "0");
        params.put("intro", mVO.getIntroduction());
        params.put("url", mVO.getPlayUrl());
        params.put("contentId", videoID);
        params.put("type", "19");

        OkHttpUtil.post(activity, URL.URL_VIDEO_STORE, "", params, mHandler, MSG_S_2, MSG_F_2);

    }

    //取消收藏
    protected void cancelStore() {
        isStore = false;
        HttpParams params = new HttpParams();
        params.put("user", UserXML.getUserId(activity));
        params.put("contentId", videoID);
        params.put("type", "19");

        OkHttpUtil.post(activity, URL.URL_VIDEO_CANCEL_STORE, "", params, mHandler, MSG_S_3, MSG_F_3);

    }

    //是否收藏
    protected void isStore() {
        HttpParams params = new HttpParams();
        params.put("user", UserXML.getUserId(activity));
        params.put("contentId", videoID);
        params.put("type", "19");

        OkHttpUtil.post(activity, URL.URL_VIDEO_IS_STORE, "", params, mHandler, MSG_S_1, MSG_F_1);

    }

    protected void onPause() {
        super.onPause();
        mVideoView.pause();
        mIsActivityPaused = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
        mVideoView.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
    }

    public void onClickRotate(View v) {
        mRotation = (mRotation + 180) % 360;
        mVideoView.setDisplayOrientation(mRotation);
    }

    public void onClickSwitchScreen(View v) {
        mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
    }


    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {
            boolean isNeedReconnect = false;
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    showToast("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    showToast("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    showToast("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    showToast("Connection timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    showToast("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    showToast("Stream disconnected !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    showToast("Network IO Error !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
                    showToast("Unauthorized Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
                    showToast("Prepare timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
                    showToast("Read frame timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_HW_DECODE_FAILURE:
                    setOptions(AVOptions.MEDIA_CODEC_SW_DECODE);
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                    break;
                default:
                    showToast("unknown error !");
                    break;
            }
            // Todo pls handle the error status here, reconnect or call finish()
            if (isNeedReconnect) {
                sendReconnectMessage();
            } else {
                finish();
            }
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };

    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
//            showToast("播放完成!");
//            finish();
        }
    };


    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_S_0:
                        mVO = FastJsonUtil.getBean(msg.obj.toString(), SmallVideoDetailVO.class);
                        setView();
                        break;
                    case MSG_F_0:

                        break;
                    case MSG_S_1:
                        String s = FastJsonUtil.getString(msg.obj.toString());
                        isStore = "true".equals(s);
                        if (isStore) {
                            tvCollect.setIconNormal(getResources().getDrawable(R.drawable.ic_v_collect2));
                        } else {
                            tvCollect.setIconNormal(getResources().getDrawable(R.drawable.ic_v_collect));
                        }
                        break;
                }
            }
        };
    }

    //渲染页面
    private void setView() {

        if (mVO != null) {
            tvName.setText(mVO.getPerson().getUserName());
            FrescoUtil.showImageSmall(mVO.getPerson().getHeadPortrait(), sdvImg);
            //收藏量
            tvCollect.setText(mVO.getCollectNum());
            //点赞量
            tvZan.setText(mVO.getPraiseNum());
            //评论量
            tvComment.setText(mVO.getEvaluationNum());

            //是否点赞
            if ("1".equals(mVO.getIsPraise())) {
                isZan = true;
                tvZan.setIconNormal(getResources().getDrawable(R.drawable.ic_v_zan2));
            } else {
                isZan = false;
                tvZan.setIconNormal(getResources().getDrawable(R.drawable.ic_v_zan));
            }

            //是否关注
            if ("1".equals(mVO.getPerson().getIsFollow())) {
                tvFollow.setText("已关注");
                tvFollow.setTextColor(getResources().getColor(R.color.colorFontBlack));
                tvFollow.setBackgroundResource(R.color.colorFontLightGrayB);
            }else{
                tvFollow.setText("关注");
                tvFollow.setTextColor(getResources().getColor(R.color.colorWhite));
                tvFollow.setBackgroundResource(R.color.colorFontRed);
            }

            //设置播放URL
            mVideoPath = mVO.getPlayUrl();
            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();

            //浏览次数+1
            BusinessAccount.appBrowse(activity, videoID, "19", mVO.getTitle(), mVO.getPlayUrl(), mHandler);
        }


    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }


    private void sendReconnectMessage() {
        if (isFinishing() || mLoadingView == null)
            return;
        showToast("正在重连...");
        mLoadingView.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (mIsActivityPaused) {
                finish();
                return;
            }
            if (!Utils.isNetworkAvailable(SmallVideoActivity.this)) {
                sendReconnectMessage();
                return;
            }
            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.img_fullscreen)
    public void onViewClicked() {

        if (mViewGroupActionBar.getVisibility() == View.VISIBLE) {
            mViewGroupActionBar.setVisibility(View.GONE);
            mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            imgFullscreen.setImageResource(R.drawable.icon_fullscreen_shrink);
            full(true);
        } else {
            mViewGroupActionBar.setVisibility(View.VISIBLE);
            mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_FIT_PARENT);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            imgFullscreen.setImageResource(R.drawable.icon_fullscreen_stretch);
            full(false);
        }
    }

    private void full(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    @OnClick({R.id.tv_collect, R.id.tv_zan, R.id.tv_comment, R.id.tv_share, R.id.layout_user,R.id.tv_follow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_collect:
                if (isStore) {
                    //如果收藏则取消收藏
                    cancelStore();
                    tvCollect.setIconNormal(getResources().getDrawable(R.drawable.ic_v_collect));
                    if (Integer.parseInt(tvCollect.getText().toString()) > 1)
                        tvCollect.setText(String.valueOf(Integer.parseInt(tvCollect.getText().toString()) - 1));
                } else {
                    store();
                    tvCollect.setIconNormal(getResources().getDrawable(R.drawable.ic_v_collect2));
                    tvCollect.setText(String.valueOf(Integer.parseInt(tvCollect.getText().toString()) + 1));
                }
                break;
            case R.id.tv_zan:
                if (isZan) {
                    //如果收藏则取消收藏
                    cancelZan();
                    tvZan.setIconNormal(getResources().getDrawable(R.drawable.ic_v_zan));
                    if (Integer.parseInt(tvZan.getText().toString()) > 1)
                        tvZan.setText(String.valueOf(Integer.parseInt(tvZan.getText().toString()) - 1));
                } else {
                    zan();
                    tvZan.setIconNormal(getResources().getDrawable(R.drawable.ic_v_zan2));
                    tvZan.setText(String.valueOf(Integer.parseInt(tvZan.getText().toString()) + 1));
                }
                break;
            case R.id.tv_comment:
                callJsMethod("setItem", new String[]{"comment-object-id", videoID});
                go(CommentActivity.class);
                break;
            case R.id.tv_share:

                break;
            case R.id.layout_user:
                if (mVO != null){
                    callJsMethod("setItem", new String[]{"person-id", mVO.getUserAccId()});
                    go(PersonActivity.class);
                }
                break;
            case R.id.tv_follow:
                if ("关注".equals(tvFollow.getText().toString())){
                    tvFollow.setText("已关注");
                    tvFollow.setTextColor(getResources().getColor(R.color.colorFontBlack));
                    tvFollow.setBackgroundResource(R.color.colorFontLightGrayB);
                    BusinessAccount.appFollow(activity, mVO.getUserAccId(), "20", mVO.getTitle(), mVO.getPlayUrl(), mHandler);
                }else{
                    tvFollow.setText("关注");
                    tvFollow.setTextColor(getResources().getColor(R.color.colorWhite));
                    tvFollow.setBackgroundResource(R.color.colorFontRed);
                    BusinessAccount.appFollowCancel(activity, mVO.getUserAccId(), "20", mVO.getTitle(), mVO.getPlayUrl(), mHandler);
                }

                break;
        }
    }

    public void cancelZan() {
        isZan = false;
        BusinessAccount.appPraiseCancel(activity, videoID, "19", mVO.getTitle(), mVO.getPlayUrl(), mHandler);
    }

    public void zan() {
        isZan = true;
        BusinessAccount.appPraise(activity, videoID, "19", mVO.getTitle(), mVO.getPlayUrl(), mHandler);
    }


}